<template>
  <div class="app-container">
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">
          {{getTitleByName(nameOfPermission)}}列表查询
          <el-button link @click="delFav()" style="margin-bottom: 5px;" v-if="userFavorites?.length > 0">
            <svg-icon icon-class="stars" color="#E6A23C" />
          </el-button>
          <el-button link @click="addFav()" style="margin-bottom: 5px;" v-else>
            <svg-icon icon-class="star" />
          </el-button>
        </div>
        <div>
          <el-button v-waves type="success" icon="Search" @click="handleFilter">
            查询
          </el-button>
          <el-button icon="Refresh" @click="handleResetQuery">
            重置
          </el-button>
        </div>
      </el-col>
    </el-row>
    <div class="filter-container">
      <el-form :inline="true" ref="listQuery" :model="listQuery" class="demo-form-inline">
        <el-form-item prop="dictTypeId" label="数据字典类型">
          <el-select v-model="listQuery.dictTypeId" class="m-2" placeholder="请选择" style="width: 300px;" clearable filterable>
            <el-option v-for="item in dictTypeList" :key="item.id" :label="`${item.dictType} - ${item.dictName} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
          </el-select>
        </el-form-item>
        <el-form-item prop="dictType" label="数据字典类型编码">
          <InputTagDialog v-model="listQuery.dictType" placeholder="数据字典类型编码" title="填写数据字典类型编码" />
        </el-form-item>
        <el-form-item prop="dictKey" label="数据字典值">
          <el-input v-model="listQuery.dictKey" placeholder="数据字典值" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="dictValue" label="数据字典名称">
          <el-input v-model="listQuery.dictValue" placeholder="数据字典名称" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="state" label="状态">
          <el-radio-group v-model="listQuery.state">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('CommonEnableDisable')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="weight" label="优先级权重">
          <el-input v-model="listQuery.weight" placeholder="优先级权重" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="elTagType" label="标签类型">
          <el-radio-group v-model="listQuery.elTagType">
            <el-radio-button label="" key="">全部</el-radio-button>
            <el-radio-button v-for="(item,index) in getEnumList('CommonElType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="elTagClass" label="标签class">
          <el-input v-model="listQuery.elTagClass" placeholder="标签class" @keyup.enter="handleFilter" />
        </el-form-item>
        <el-form-item prop="elTagStyle" label="标签样式">
          <el-input v-model="listQuery.elTagStyle" placeholder="标签样式" @keyup.enter="handleFilter" />
        </el-form-item>
      </el-form>
    </div>
    <el-row :gutter="20">
      <el-col :span="24" class="custom-title-box">
        <div class="custom-info-title">列表详情</div>
        <div>
          <el-button v-show="checkAuthByCode('')" type="primary" icon="Download" @click="handleExport">
            导出
          </el-button>
          <el-button type="primary" icon="Edit" :disabled="!checkAuthByCode('')" @click="handleAdd">
            新增
          </el-button>
        </div>
      </el-col>
    </el-row>
    <el-divider class="el-divider--horizontal-margin" />
    <el-table v-loading="listLoading"
              :key="tableKey"
              :data="list"
              :row-style="{height: '0'}"
              :cell-style="{padding: '0'}"
              border
              fit
              highlight-current-row
              tooltip-effect="dark"
              @sort-change="handleSortChange"
              @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="39px" />
      <el-table-column align="center" type="index" label="序号" width="60px" />
      <el-table-column v-if="isDebug" align="center" label="ID" prop="id" width="60px" sortable show-overflow-tooltip />
      <!--
      <el-table-column align="center" label="数据字典类型ID" prop="dictTypeId" min-width="205px" sortable show-overflow-tooltip />
      -->
      <el-table-column align="center" label="数据字典类型编码" prop="dictType" min-width="220px" sortable show-overflow-tooltip>
        <template v-slot="{row}"><CodeTag :code="row.dictType" /></template>
      </el-table-column>
      <el-table-column align="center" label="数据字典值" prop="dictKey" min-width="130px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.dictKey }}</template>
      </el-table-column>
      <el-table-column align="center" label="数据字典名称" prop="dictValue" min-width="155px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.dictValue }}</template>
      </el-table-column>
      <el-table-column align="center" label="状态" prop="state" min-width="80px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonEnableDisable')" :enum-key="row.state" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="优先级权重" prop="weight" min-width="120px" sortable show-overflow-tooltip />
      <el-table-column align="center" label="标签类型" prop="elTagType" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">
          <EnumTag :enum-list="getEnumList('CommonElType')" :enum-key="row.elTagType" />
        </template>
      </el-table-column>
      <el-table-column align="center" label="标签class" prop="elTagClass" min-width="180px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.elTagClass }}</template>
      </el-table-column>
      <el-table-column align="center" label="标签样式" prop="elTagStyle" min-width="120px" sortable show-overflow-tooltip>
        <template v-slot="{row}">{{ row.elTagStyle }}</template>
      </el-table-column>
      <el-table-column align="center" label="创建时间" width="180px" prop="createTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.createTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="最后修改时间" width="180px" prop="updateTime" sortable show-overflow-tooltip>
        <template v-slot="{row}"><DateTag :timestamp="row.updateTime" /></template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="160px" fixed="right">
        <template v-slot="{row}">
          <el-button type="primary" link @click="handleView(row)">查看</el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text="确定"
                         cancel-button-text="取消"
                         :icon="WarningFilled"
                         icon-color="#626AEF"
                         title="您确定删除么？"
                         @confirm="handleDelete(row)"
                         v-if="checkAuthByCode('')">
            <template #reference>
              <el-button type="danger" link>删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-model:total="total" v-model:page="listQuery.pageNum" v-model:limit="listQuery.pageSize" @pagination="getList" />
    <el-dialog v-model="dialogVisible" :title="dialogTypeTitle" width="70%" top="2vh">
      <el-form class="my-form" ref="obj" :model="obj" :rules="rules" label-position="right" :disabled="dialogType === 'view'" label-width="auto" label-suffix="：">
        <el-form-item v-show="isDebug" label="ID">
          <text>{{ obj.id }}</text>
        </el-form-item>
        <el-form-item label="数据字典类型" prop="dictTypeId">
          <el-select v-model="obj.dictTypeId" class="m-2" placeholder="请选择" style="width: 300px;" clearable filterable>
            <el-option v-for="item in dictTypeList" :key="item.id" :label="`${item.dictType} - ${item.dictName} ${item.state === '0' ? '【已禁用】' : ''}`" :value="item.id" :disabled="item.state === '0'" />
          </el-select>
        </el-form-item>
        <!--
        <el-form-item label="数据字典类型编码" prop="dictType">
          <el-input v-model="obj.dictType" placeholder="请输入数据字典类型编码，最多输入50个字符" />
        </el-form-item>
        -->
        <el-form-item label="数据字典值" prop="dictKey">
          <el-input v-model="obj.dictKey" placeholder="请输入数据字典值，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="数据字典名称" prop="dictValue">
          <el-input v-model="obj.dictValue" placeholder="请输入数据字典名称，最多输入200个字符" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="obj.state">
            <el-radio-button v-for="(item,index) in getEnumList('CommonEnableDisable')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="优先级权重" prop="weight">
          <el-input-number v-model="obj.weight" placeholder="请输入优先级权重" :min="0" :precision="0" />
        </el-form-item>
        <el-form-item label="标签类型" prop="elTagType">
          <el-radio-group v-model="obj.elTagType">
            <el-radio-button v-for="(item,index) in getEnumList('CommonElType')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签class" prop="elTagClass">
          <el-input v-model="obj.elTagClass" placeholder="请输入标签class，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="标签样式" prop="elTagStyle">
          <el-input v-model="obj.elTagStyle" placeholder="请输入标签样式，最多输入100个字符" />
        </el-form-item>
        <el-form-item label="创建时间">
          <text>{{ obj.createTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item label="最后修改时间">
          <text>{{ obj.updateTime || '自动生成' }}</text>
        </el-form-item>
        <el-form-item v-show="isDebug" label="数据版本">
          <text>{{ obj.version }}</text>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="info" icon="Close" @click="dialogVisible=false">关闭</el-button>
        <el-button type="primary" icon="Check" v-show="dialogType !== 'view'" @click="doConfirm('obj')">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost, doPut, doDelete, doGetDownload} from '@/config/http'
import {alertErrorMsg, customValidator, getListPageSize, notifySuccess, svc} from '@/config/common'
import InputTagDialog from '@/components/InputTag/inputTagDialog.vue';
import SvgIcon from '@/components/SvgIcon/index.vue';
import initListStore from '@/store/modules/initList'

const emptyObj = {
  dictTypeId: null, // 数据字典类型ID
  dictType: null, // 数据字典类型编码
  dictKey: null, // 数据字典值
  dictValue: null, // 数据字典名称
  state: null, // 状态
  weight: null, // 优先级权重
  elTagType: null, // 标签类型
  elTagClass: null, // 标签class
  elTagStyle: null, // 标签样式
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'dictValue_nocache',
  components: {SvgIcon, InputTagDialog},
  mixins: [baseConfig],
  data() {
    const svc = 'icims-api'
    return {
      svc,
      obj: Object.assign({}, emptyObj),
      routes: [],
      nameOfPermission: null,
      dialogVisible: false,
      dialogType: 'add',
      dialogTypeTitle: '新增',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      listQuery: {
        pageNum: 1,
        pageSize: 10,
        sortField: 'id',
        sortType: 'desc',
        dictTypeId: null,
        dictType: null,
        dictKey: null,
        dictValue: null,
        state: null,
        weight: null,
        elTagType: null,
        elTagClass: null,
        elTagStyle: null,
        createTimeStart: null,
        createTimeEnd: null,
        updateTimeStart: null,
        updateTimeEnd: null,
      },
      selectionList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      rules: {
        dictTypeId: [{ required: true, validator: customValidator, min: 1, max: 20, label: '数据字典类型ID', trigger: ['blur', 'change'] }],
        dictType: [{ required: false, validator: customValidator, min: 1, max: 50, label: '数据字典类型编码', trigger: ['blur', 'change'] }],
        dictKey: [{ required: true, validator: customValidator, min: 1, max: 100, label: '数据字典值', trigger: ['blur', 'change'] }],
        dictValue: [{ required: true, validator: customValidator, min: 1, max: 200, label: '数据字典名称', trigger: ['blur', 'change'] }],
        state: [{ required: true, validator: customValidator, min: 1, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        weight: [{ required: false, validator: customValidator, min: 0, max: 9, label: '优先级权重', trigger: ['blur', 'change'] }],
        elTagType: [{ required: false, validator: customValidator, min: 0, max: 100, label: '标签类型', trigger: ['blur', 'change'] }],
        elTagClass: [{ required: false, validator: customValidator, min: 0, max: 100, label: '标签class', trigger: ['blur', 'change'] }],
        elTagStyle: [{ required: false, validator: customValidator, min: 0, max: 100, label: '标签样式', trigger: ['blur', 'change'] }],
      },
      dictTypeList: initListStore().dictTypeList, // 数据字典类型
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
  },
  created() {
    this.nameOfPermission = 'dictValue'
    this.getFavorite(this.nameOfPermission)?.then(res => this.userFavorites = res)
    // this.initList()
    this.getList()
  },
  methods: {
    // async initList() {
    //   let p1 = doGet(svc, '/dict-type/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1])
    //   this.dictTypeList = resArray[0]['records']
    // },
    getList() {
      this.listLoading = true
      doGet(this.svc, '/dict-value/page', this.listQuery).then(res => {
        this.listLoading = false
        this.list = res['records']
        this.total = parseInt(res['total'])
      }).catch(e => {
        console.error(e)
        this.listLoading = false
      })
    },
    handleResetQuery() {
      this.resetForm("listQuery")
    },
    handleFilter() {
      this.listQuery.pageNum = 1
      this.getList()
    },
    handleModifyStatus(row, status) {
      this.$message({
        message: '操作Success',
        type: 'success'
      })
      row.status = status
    },
    handleSelectionChange(data) {
      this.selectionList = data
    },
    handleSortChange(data) {
      const { prop, order } = data
      this.listQuery.sortField = prop
      this.listQuery.sortType = order === 'ascending' ? 'asc' : 'desc'
      this.handleFilter()
    },
    handleEdit(row) {
      this.dialogType = 'edit'
      this.dialogTypeTitle = '编辑'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, row)
    },
    handleView(row) {
      this.dialogType = 'view'
      this.dialogTypeTitle = '详情'
      this.dialogVisible = true
      this.checkStrictly = false
      this.obj = Object.assign({}, row)
    },
    handleAdd() {
      this.dialogType = 'add'
      this.dialogTypeTitle = '新增'
      this.dialogVisible = true
      this.checkStrictly = true
      this.obj = Object.assign({}, emptyObj)
    },
    handleExport() {
      doGetDownload(this.svc, '/dict-value/export', this.listQuery)
    },
    handleDelete(row) {
      doDelete(this.svc, `/dict-value/${row.id}`, {}).then(() => {
        notifySuccess('操作成功')
        this.getList()
        this.dialogVisible = false
      })
    },
    async doConfirm(formName) {
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      switch (this.dialogType) {
        case 'add': {
          doPost(this.svc, '/dict-value/add', this.obj).then(() => {
            notifySuccess('新增成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        }
        case 'edit': {
          doPut(this.svc, '/dict-value/modify', this.obj).then(() => {
            notifySuccess('修改成功')
            this.getList()
            this.dialogVisible = false
          })
          break
        }
      }
    },
  }
}
</script>
